package com.kaibes.module.login;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.kaibes.core.base.util.AesUtils;
import com.kaibes.core.base.util.StringUtils;
import com.kaibes.module.account.core.AccountService;
import com.kaibes.module.account.pojo.Account;
import com.kaibes.module.token.core.TokenEncryptions;
import com.kaibes.module.token.core.TokenUtils;
import com.kaibes.module.token.pojo.Token;
import com.kaibes.module.token.pojo.TokenType;
import com.kaibes.module.token.service.TokenService;
import com.kaibes.module.verification.VerificationUtils;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.response.ResponseFactory;
import com.kaibes.web.util.UserAgentUtils;

@RestController
@RequestMapping("/logins")
public class LoginApi {

    @Autowired
    private AccountService accountService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TokenEncryptions tokenEncryptions;

    private LoginResponse createResult(LoginResultEnum result, String message) {
        LoginResponse response = new LoginResponse();
        response.setResult(result);
        response.setMessage(message);
        return response;
    }

    @PostMapping("login")
    @ApiLink(value = "登录操作", validated = false)
    public ResponseEntity<LoginResponse> post(HttpServletRequest request, HttpServletResponse response,
            @RequestBody @Validated LoginQ loginQ) {
        String verification = VerificationUtils.getCode(LoginRes.LOGIN_CODE);
        if (!Objects.equals(verification, loginQ.getVerification())) {
            return ResponseFactory.postFailure(createResult(LoginResultEnum.WRONG_VERIFICATION, "登录失败，验证码不正确"));
        }
        return postBase(request, response, loginQ);
    }

    @PostMapping("/token")
    @ApiLink(value = "无验证码登录操作", validated = false)
    public ResponseEntity<LoginResponse> postBase(HttpServletRequest request, HttpServletResponse response, 
            @RequestBody @Validated LoginQBase loginQ) {
        Account account = accountService.getByUsername(loginQ.getUsername());
        if (account == null) {
            return ResponseFactory.postFailure(createResult(LoginResultEnum.WRONG_USERNAME, "登录失败，用户不存在"));
        }

        if (!passwordEncoder.matches(loginQ.getPassword(), account.getPassword())) {
            return ResponseFactory.postFailure(createResult(LoginResultEnum.WRONG_PASSWORD, "登录失败，密码错误"));
        }
        
        String userAgent = UserAgentUtils.getUserAgentStr(request);
        TokenType type = TokenUtils.getType(userAgent);
        if (type == null) {
            return ResponseFactory.postFailure(createResult(LoginResultEnum.WRONG_DEVICE, "登录失败，不支持的登录设备"));
        }
        
        Token token = tokenService.save(loginQ.getAesKey(), loginQ.getAesIv(), loginQ.getMinutes(), account.getUserId(),
                type);
        String tokenStr;
        try {
            tokenStr = tokenEncryptions.writeToken(token);
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
                | BadPaddingException | UnsupportedEncodingException | InvalidAlgorithmParameterException
                | JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        if (token.getType() == TokenType.WEB) {
            TokenUtils.saveToken2Cookie(response, tokenStr, loginQ.getMinutes());
        }
        if (StringUtils.isNotBlank(loginQ.getAesKey())) {
            try {
                String temp;
                if (StringUtils.isNotBlank(loginQ.getAesIv())) {
                    temp = AesUtils.CBC.encrypt2String64(tokenStr, loginQ.getAesKey(), loginQ.getAesIv());
                } else {
                    temp = AesUtils.ECB.encrypt2String64(tokenStr, loginQ.getAesKey());
                }
                return ResponseFactory.postSuccess(createResult(LoginResultEnum.OK, "登录成功").setToken(temp));
            } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
                    | BadPaddingException | UnsupportedEncodingException | InvalidAlgorithmParameterException e) {
                return ResponseFactory.postFailure(createResult(LoginResultEnum.WRONG_AES_KEY, "密钥不合法"));
            }
        } else {
            return ResponseFactory.postSuccess(createResult(LoginResultEnum.OK, "登录成功").setToken(tokenStr));
        }
    }
}
